# -*- coding: UTF-8 -*-
"""
Team模式下最终得分的分数面板改造
By AnpyD
"""

# 导入模块
import bs
import bsUtils
import bsInternal
import account_system
from bs import TeamsScoreScreenActivity


# Team Series Victory Score Screen Activity Modify
class team_series_victory_score_screen_activity_modif(TeamsScoreScreenActivity):
    def __init__(self, settings={}):
        TeamsScoreScreenActivity.__init__(self, settings=settings)
        self._minViewTime = 15000
        self._isFFA = isinstance(self.getSession(), bs.FreeForAllSession)
        self._allowServerRestart = True

    def onTransitionIn(self):
        # we dont yet want music and stuff..
        TeamsScoreScreenActivity.onTransitionIn(
            self, music=None, showTips=False)

    def add_tickets(self, display_name, amount):
        for player in bsInternal._getForegroundHostActivity().players:
            if player.getName(True) == display_name:
                account_id = player.get_account_id()
                account_system.add_tickets(account_id=str(account_id), amount=amount)

    def del_tickets(self, display_name, amount):
        for player in bsInternal._getForegroundHostActivity().players:
            if player.getName(True) == display_name:
                account_id = player.get_account_id()
                account_system.del_tickets(account_id=str(account_id), amount=amount)

    def get_account_tickets(self, display_name):
        for player in bsInternal._getForegroundHostActivity().players:
            if player.getName(True) == display_name:
                account_id = player.get_account_id()
                if account_id is not None:
                    return account_system.get_data()[account_id]["tickets"]


    def onBegin(self):
        bsInternal._setAnalyticsScreen(
            'FreeForAll Series Victory Screen'
            if self._isFFA else 'Teams Series Victory Screen')

        if bs.getEnvironment()['interfaceType'] == 'large':
            s = bs.Lstr(resource='pressAnyKeyButtonPlayAgainText')
        else:
            s = bs.Lstr(resource='pressAnyButtonPlayAgainText')

        TeamsScoreScreenActivity.onBegin(
            self, showUpNext=False, customContinueMessage=s)

        winningTeam = self.settings['winner']

        # pause a moment before playing victory music
        bs.gameTimer(600, bs.WeakCall(self._playVictoryMusic))
        bs.gameTimer(4400, bs.WeakCall(
            self._showWinner, self.settings['winner']))
        bs.gameTimer(4400+200, bs.Call(bs.playSound, self._scoreDisplaySound))

        # make sure to exclude players without teams (this means they're
        # still doing selection)
        if self._isFFA:
            playersSorted = [
                [p.getTeam().sessionData['score'],
                 p.getName(full=True),
                 p] for name, p in self.scoreSet.getValidPlayers().items()
                if p.getTeam() is not None]
            playersSorted.sort(reverse=True)
        else:
            playersSorted = [
                [p.score, p.nameFull, p]
                for name, p in self.scoreSet.getValidPlayers().items()]
            playersSorted.sort(reverse=True)

        tsHeight = 300
        tsHOffs = -390
        t = 6400
        tIncr = 120

        if self._isFFA:
            txt = bs.Lstr(value='${A}:',
                          subs=[('${A}', bs.Lstr(
                              resource='firstToFinalText', subs=[
                                  ('${COUNT}',
                                   str(self.getSession()._ffaSeriesLength))]))])
        else:
            # some languages may prefer to always show 'first to X' instead of
            # 'best of X' FIXME - this will affect all clients connected to
            # us even if they're not using a language with this enabled.. not
            # the end of the world but something to be aware of.
            if bsUtils._getResource('bestOfUseFirstToInstead'):
                txt = bs.Lstr(value='${A}:', subs=[
                    ('${A}', bs.Lstr(resource='firstToFinalText', subs=[
                        ('${COUNT}',
                         str(self.getSession()._seriesLength/2+1))]))])
            else:
                txt = bs.Lstr(value='${A}:', subs=[
                    ('${A}', bs.Lstr(resource='bestOfFinalText', subs=[
                        ('${COUNT}', str(self.getSession()._seriesLength))]))])

        bsUtils.Text(txt,
                     vAlign='center',
                     maxWidth=300,
                     color=(0.5, 0.5, 0.5, 1.0), position=(0, 220),
                     scale=1.2, transition='inTopSlow', hAlign='center',
                     transitionDelay=tIncr*4).autoRetain()

        winScore = (self.getSession()._seriesLength-1)/2+1
        loseScore = 0
        for team in self.teams:
            if team.sessionData['score'] != winScore:
                loseScore = team.sessionData['score']

        if not self._isFFA:
            bsUtils.Text(
                bs.Lstr(
                    resource='gamesToText',
                    subs=[('${WINCOUNT}', str(winScore)),
                          ('${LOSECOUNT}', str(loseScore))]),
                color=(0.5, 0.5, 0.5, 1.0),
                maxWidth=160, vAlign='center', position=(0, -215),
                scale=1.8, transition='inLeft', hAlign='center',
                transitionDelay=4800 + tIncr * 4).autoRetain()

        if self._isFFA:
            vExtra = 120
        else:
            vExtra = 0

        """
        Modif
        添加点券
        """
        for player in bsInternal._getForegroundHostActivity().players:
            for p in playersSorted:
                if player.getName(True) == p[1]:
                    account_id = player.get_account_id()
                    if account_id is not None:
                        if p[2].score == 0:
                            _amount = 0
                        else:
                            _amount = int(p[2].score/10) + 1
                        if p[2].getTeam() == winningTeam:
                            _amount += 10
                        account_system.add_tickets(account_id=str(account_id), amount=_amount)
                        account_system.add_score(account_id=str(account_id), score=int(p[2].score/1.5)+1)
        bs.playSound(bs.getSound('cashRegister'))

        # 最有价值的玩家
        if not self._isFFA:
            mvp, mvpName = None, None
            for p in playersSorted:
                if p[2].getTeam() == winningTeam:
                    mvp = p[2]
                    mvpName = p[1]
                    break
            if mvp is not None:
                self.add_tickets(display_name=mvpName, amount=10)
                _mvp_text = str(mvpName) + "\n  +" + str(10) + " " + bs.getSpecialChar('ticket')
                bsUtils.Text(text=bs.Lstr(resource='mostValuablePlayerText'),
                             color=(0.6, 0.5, 0.4),
                             vAlign='center',
                             maxWidth=300,
                             position=(180, tsHeight/2+15), transition='inLeft',
                             hAlign='left', transitionDelay=t).autoRetain()
                t += 4*tIncr

                bsUtils.Image(
                    mvp.getIcon(),
                    position=(230, tsHeight / 2 - 55 + 14 - 5),
                    scale=(70, 70),
                    transition='inLeft', transitionDelay=t).autoRetain()
                bsUtils.Text(text=_mvp_text,
                    position=(280, tsHeight / 2 - 55 + 15 - 5),
                    hAlign='left', vAlign='center', maxWidth=170, scale=1.3,
                    color=bs.getSafeColor(mvp.getTeam().color + (1,)),
                    transition='inLeft', transitionDelay=t).autoRetain()
                t += 4*tIncr

        # 最暴力的玩家
        mostKills = 0
        for p in playersSorted:
            if p[2].killCount >= mostKills:
                mvp = p[2]
                mvpName = p[1]
                mostKills = p[2].killCount
        if mvp is not None:
            self.add_tickets(display_name=mvpName, amount=10)
            _mvp2_text = str(mvpName)+"\n  +" + str(int(5+mostKills/10)) + " " + bs.getSpecialChar('ticket')
            bsUtils.Text(text=bs.Lstr(resource='mostViolentPlayerText'),
                         color=(0.6, 0.5, 0.4),
                         vAlign='center',
                         maxWidth=300,
                         position=(180, tsHeight/2-150+vExtra+15),
                         transition='inLeft',
                         hAlign='left', transitionDelay=t).autoRetain()
            bsUtils.Text(
                bs.Lstr(
                    value='(${A})',
                    subs=[('${A}', bs.Lstr(
                        resource='killsTallyText',
                        subs=[('${COUNT}', str(mostKills))]))]),
                position=(260, tsHeight / 2 - 150 - 15 + vExtra),
                color=(0.3, 0.3, 0.3, 1.0),
                scale=0.6, hAlign='left', transition='inLeft',
                transitionDelay=t).autoRetain()
            t += 4*tIncr

            bsUtils.Image(
                mvp.getIcon(),
                position=(233, tsHeight / 2 - 150 - 30 - 46 + 25 + vExtra),
                scale=(50, 50),
                transition='inLeft', transitionDelay=t).autoRetain()
            bsUtils.Text(text=_mvp2_text,
                position=(270, tsHeight / 2 - 150 - 30 - 36 + vExtra + 15),
                hAlign='left', vAlign='center', maxWidth=180,
                color=bs.getSafeColor(mvp.getTeam().color + (1,)),
                transition='inLeft', transitionDelay=t).autoRetain()
            t += 4*tIncr

        # 最遭受暴力的玩家
        mostKilled = 0
        mkp, mkpName = None, None
        for p in playersSorted:
            if p[2].killedCount >= mostKilled:
                mkp = p[2]
                mkpName = p[1]
                mostKilled = p[2].killedCount
        if mkp is not None:
            if self.get_account_tickets(display_name=mkpName) == 0:
                _del_ticket = 0
            elif self.get_account_tickets(display_name=mkpName) < int(5+mostKilled/10):
                _del_ticket = self.get_account_tickets(display_name=mkpName)
                self.del_tickets(display_name=mkpName, amount=_del_ticket)
            else:
                _del_ticket = int(5+mostKilled/10)
            
            _mkp_text = str(mkpName)+"\n  -" + str(_del_ticket) + " " + bs.getSpecialChar('ticket')
            
            bsUtils.Text(text=bs.Lstr(resource='mostViolatedPlayerText'),
                         color=(0.6, 0.5, 0.4),
                         vAlign='center',
                         maxWidth=300,
                         position=(180, tsHeight/2-300+vExtra+15),
                         transition='inLeft',
                         hAlign='left', transitionDelay=t).autoRetain()
            bsUtils.Text(
                bs.Lstr(
                    value='(${A})',
                    subs=[('${A}', bs.Lstr(
                        resource='deathsTallyText',
                        subs=[('${COUNT}', str(mostKilled))]))]),
                position=(260, tsHeight / 2 - 300 - 15 + vExtra),
                hAlign='left', scale=0.6, color=(0.3, 0.3, 0.3, 1.0),
                transition='inLeft', transitionDelay=t).autoRetain()
            t += 4*tIncr
            bsUtils.Image(
                mkp.getIcon(),
                position=(233, tsHeight / 2 - 300 - 30 - 46 + 25 + vExtra),
                scale=(50, 50),
                transition='inLeft', transitionDelay=t).autoRetain()
            bsUtils.Text(text=_mkp_text,
                         position=(270, tsHeight/2-300-30-36+vExtra+15),
                         hAlign='left', vAlign='center',
                         color=bs.getSafeColor(mkp.getTeam().color+(1,)),
                         maxWidth=180, transition='inLeft',
                         transitionDelay=t).autoRetain()
            t += 4*tIncr

        
        # 显示所有玩家比赛结果
        tDelay = t
        bsUtils.Text(text=bs.Lstr(resource='finalScoresText'),
                     color=(0.5, 0.5, 0.5, 1.0),
                     position=(tsHOffs, tsHeight/2),
                     transition='inRight',
                     transitionDelay=tDelay).autoRetain()
        tDelay += 4*tIncr

        vOffs = 0.0
        tDelay += len(playersSorted) * 8*tIncr
        for score, name, p in playersSorted:
            tDelay -= 4*tIncr
            vOffs -= 40

            if p.score == 0:
                _player_tickets = 0
            else:
                _player_tickets = int(p.score/10) + 1

            _player_final_achievement = str(p.score) + "    +" + str(_player_tickets) + " " + bs.getSpecialChar('ticket')
            bsUtils.Text(str(_player_final_achievement),
                         color=p.getTeam().color,
                         position=(tsHOffs + 240, tsHeight / 2 + vOffs),
                         hAlign='right', transition='inRight',
                         transitionDelay=tDelay).autoRetain()
            tDelay -= 4*tIncr

            bsUtils.Image(
                p.getIcon(),
                position=(tsHOffs - 92, tsHeight / 2 + vOffs + 15),
                scale=(30, 30),
                transition='inLeft', transitionDelay=tDelay).autoRetain()
            bsUtils.Text(
                bs.Lstr(value=name),
                position=(tsHOffs - 70, tsHeight / 2 + vOffs + 15),
                hAlign='left', vAlign='center', maxWidth=180,
                color=bs.getSafeColor(p.getTeam().color + (1,)),
                transition='inRight', transitionDelay=tDelay).autoRetain()

        bs.gameTimer(15000, bs.WeakCall(self._showTips))

    def _showTips(self):
        self._tipsText = bsUtils.TipsText(offsY=70)

    def _playVictoryMusic(self):
        # make sure we dont stomp on the next activity's music choice
        if not self.isTransitioningOut():
            bs.playMusic('Victory')

    def _showWinner(self, team):
        if not self._isFFA:
            offsV = 0
            bsUtils.ZoomText(team.name, position=(0, 97),
                             color=team.color, scale=1.15, jitter=1.0,
                             maxWidth=250).autoRetain()
        else:
            offsV = -80
            if len(team.players) == 1:
                i = bsUtils.Image(
                    team.players[0].getIcon(),
                    position=(0, 143),
                    scale=(100, 100)).autoRetain()
                bsUtils.animate(i.node, 'opacity', {0: 0.0, 250: 1.0})
                bsUtils.ZoomText(bs.Lstr(
                    value=team.players[0].getName(
                        full=True, icon=False)),
                    position=(0, 97 + offsV),
                    color=team.color, scale=1.15, jitter=1.0,
                    maxWidth=250).autoRetain()

        sExtra = 1.0 if self._isFFA else 1.0

        # some languages say "FOO WINS" differently for teams vs players
        if isinstance(self.getSession(), bs.FreeForAllSession):
            winsResource = 'seriesWinLine1PlayerText'
        else:
            winsResource = 'seriesWinLine1TeamText'
        winsText = bs.Lstr(resource=winsResource)
        # temp - if these come up as the english default, fall-back to the
        # unified old form which is more likely to be translated

        bsUtils.ZoomText(winsText, position=(0, -10 + offsV),
                         color=team.color, scale=0.65 * sExtra, jitter=1.0,
                         maxWidth=250).autoRetain()
        bsUtils.ZoomText(bs.Lstr(resource='seriesWinLine2Text'),
                         position=(0, -110 + offsV),
                         scale=1.0 * sExtra, color=team.color, jitter=1.0,
                         maxWidth=250).autoRetain()
        _winner_team_text = "此队伍所有成员获取 10 " + bs.getSpecialChar('ticket')
        bsUtils.ZoomText(text=_winner_team_text,
                         color=team.color,
                         scale=0.35 * sExtra,
                         jitter=1.0,
                         position=(-60, -180 + offsV)).autoRetain()